package model

import (
	"gorm.io/gorm"
	__ "video-srv/basic/proto/rpc"
)

type Video struct {
	gorm.Model
	UserId       int    `gorm:"type:int" json:"userId"`
	Title        string `gorm:"type:varchar(30)" json:"title"`
	Image        string `gorm:"type:varchar(255)" json:"image"`
	Tags         string `gorm:"type:varchar(30)" json:"tags"`
	Refer        string `gorm:"type:varchar(30)" json:"refer"`
	Status       int    `gorm:"type:int" json:"status"`
	AreaName     string `gorm:"type:varchar(30)" json:"areaName"`
	CategoryName string `gorm:"type:varchar(30)" json:"categoryName"`
	ChannelName  string `gorm:"type:varchar(30)" json:"channelName"`
	YearName     string `gorm:"type:varchar(30)" json:"yearName"`
}

type CheckVideo struct {
	gorm.Model
	UserId  int    `gorm:"type:int" json:"userId"`
	VideoId int    `gorm:"type:int" json:"videoId"`
	Status  int    `gorm:"type:int" json:"status"`
	Reason  string `gorm:"type:varchar(30)" json:"reason"`
}

func (v *Video) GetVideoById(db *gorm.DB, videoId int) error {
	return db.Where("id = ?", videoId).First(&v).Error
}

func (v *Video) PublishVideo(db *gorm.DB) error {
	return db.Create(&v).Error
}

func (c *CheckVideo) CheckVideo(db *gorm.DB) error {
	return db.Create(&c).Error
}

func (v *Video) UpdateVideoStatus(db *gorm.DB, videoId, status int) error {
	return db.Model(&v).Where("id = ?", videoId).Update("status", status).Error
}

func (v *Video) GetVideoList(db *gorm.DB, userId, page, size int) (list []*__.VideoItem, err error) {
	offset := (page - 1) * size
	err = db.Model(&v).Select("id,title,image,tags,refer,area_name,category_name,channel_name,year_name").
		Where("user_id = ?", userId).Offset(offset).Limit(size).Find(&list).Error
	return
}

func (v *Video) SearchVideoList(db *gorm.DB, areaName, categoryName, channelName, yearName string) (list []*__.VideoItem, err error) {
	query := db.Model(&v).Select("title,image,tags,refer,area_name,category_name,channel_name,year_name")
	if areaName != "" {
		query.Where("area_name = ?", areaName)
	}
	if categoryName != "" {
		query.Where("category_name = ?", categoryName)
	}
	if channelName != "" {
		query.Where("channel_name = ?", channelName)
	}
	if yearName != "" {
		query.Where("year_name = ?", yearName)
	}
	err = query.Find(&list).Error
	return
}
